/*
 *   Copyright (c) 2007-2008 Seesmic
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
if (typeof seesmic == 'undefined') { var seesmic = {}; }
seesmic.widget = new function () {
  this.callback =  function (data) {
    var _esc = function (s) {
      while (s.indexOf('Re: Re: ') > -1) {
        s = s.substr(4);
      }
      return s.replace(/&/gm, '&amp;').replace(/</gm, '&lt;')
        .replace(/>/gm, '&gt;').replace(/"/gm, '&quot;');
    }
    var s = '<table>';
    var vid;
    var r;
    for (var i = 0; i < data.length; i++) {
      vid = data[i];
      r = '<tr><td><div><a href="' + vid.url_player + '"><img src="' +
        vid.url_thumbnail + '" width="40" height="30" style="border: 0px;" alt=""/>' +
        '</a></div></td><td><a href="' + vid.url_player + '">' + _esc(vid.title) +
        '</a><br/>' + this.relativeTime(this.parseISO8601(vid.created_at)) +
        '</td></tr>';
      s += r;
    }
    s += '</table>';
    document.getElementById('seesmicJSWidgetList').innerHTML = s;
  };
  this.parseISO8601 = function (str) {
    var arr = str.split('T');
    var dt = arr[0];
    var tm = arr[1];
    arr = tm.split('.');
    tm = arr[0];
    dt = dt.split('-');
    tm = tm.split(':');
    for (var i in dt) { dt[i] = parseInt(dt[i], 10); }
    for (var i in tm) { tm[i] = parseInt(tm[i], 10); }
    return new Date(dt[0], dt[1] - 1, dt[2], tm[0], tm[1], tm[2]);
  };
  this.relativeTime = function (dt) {
    var diff = (new Date().getTime() - dt.getTime()) / 1000;
    var ret;
    switch (true) {
      case diff < 60:
        ret = 'less than a minute ago';
        break;
      case diff < 120:
        ret = 'about a minute ago';
        break;
      case diff < (45*60):
        ret = parseInt((diff / 60), 10) + ' minutes ago';
        break;
      case diff < (120*60):
        ret = 'about an hour ago'
        break;
      case diff < (24*60*60):
        ret = 'about ' + parseInt((diff / 3600), 10) + ' hours ago';
        break;
      case diff < (48*60*60):
        ret = 'one day ago';
        break;
      default:
        ret = parseInt((diff / 86400), 10) + ' days ago';
        break;
    }
    return ret;
  };
};

